<?php

namespace App\Http\Controllers\V1\Informations;

use App\Http\Requests\V1\NoticeRequest;
use App\Models\V1\Faculty;
use App\Models\V1\InfoNotice;
use App\Models\V1\InfoNoticeProgram;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use Log;
class NoticeDetailsController extends Controller
{

    /**
     * 显示数据管理页面
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('v1.notice');
    }

    /**
     * 获取数据
     *
     * @param Request $request
     */
    public function postIndex(Request $request)
    {
        $response = [
            'code' => 1,
            'msg' => '',
            'count' => 0,
            'data' => [],
        ];

        // 获取符合查询条件的数据
        $currentPage = $request->get('page');
        $rows = $request->get('limit');
        $keywords = $request->get('keywords');

        // 获取符合查询条件的数据
        $data = $this->getDataList($currentPage, $rows, $keywords);

        if (!$data->isEmpty()) {

            $formatList = array();

            $count = $data->total() > 0 ? $data->total() : 0;

            if ($count > 0) {
                // 格式化数据
                foreach ($data->items() as $item) {
                    $formatItem['code'] = $item['code'];
                    $objProgram = $this->getNoticeProgramByCode($item['program_code']);
                    $formatItem['program_code'] = empty($objProgram) ? "未知" : $objProgram['name'];
                    $formatItem['type'] = $this->formateTypeData($item['type']);
                    $formatItem['title'] = $item['title'];
                    $content = json_decode($item['content']);
                    if (count($content)>0) {
                        $formatItem['content'] = $content[0]->content;
                    }else {
                        $formatItem['content'] = '';
                    }
                    $formatItem['isShow'] = $this->formateMobileShowData($item['isShow']);
                    $objPublisher = $this->getFacultyByCode($item['publisher_code']);
                    $formatItem['publisher_code'] = empty($objPublisher) ? "未知" : $objPublisher['name'];
                    $formatItem['updated_at'] = $item['updated_at']->format('Y-m-d H:i:s');
                    $formatItem['created_at'] = $item['created_at']->format('Y-m-d H:i:s');
                    array_push($formatList, $formatItem);
                }
                $response['code'] = 0;
                $response['msg'] = '加载数据成功';
                $response['count'] = $count;
                $response['data'] = $formatList;
            }
        }

        return $response;
    }

    /**
     * 进入单条数据新增前，内容选择界面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function typeView(Request $request)
    {
        $data['view'] = $request->input('view');
        return view('v1.form.notice_item_type', $data);
    }

    /**
     * 进入单条数据显示界面（适用于新增addData、查看viewData、编辑editData功能）
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showView(Request $request)
    {
        $loginUser = Auth::user();
        $data['view'] = $request->input('view');

        switch ($request->input('view')) {
            case 'addData':
                $data['type'] = isset($request['type']) ? $request->input('type') : '';
                $data['publisher'] = $loginUser['code'];
                $data['randomCode'] = 'NC' . uniqid();
                $data['programs'] = $this->getNoticeProgramList();
                $viewName = $this->geAddFormByType($data['type']);
                return view($viewName, $data);
                break;
            case 'editData':
                $currentNews = $this->getNoticeByCode($request->input('code'));
                $content = json_decode( $currentNews['content'],true);
                $currentNews['content']=$this->getContentToHtml($content);
                $data['itemData'] = $currentNews;
                $data['programs'] = $this->getNoticeProgramList();
                $data['isShow'] = $this->formateMobileShowData($currentNews['isPublish']);
                $viewName = $this->geAddFormByType($currentNews['type']);
                return view($viewName, $data);
                break;
            case 'previewData':
                $currentNews = $this->getNoticeByCode($request->input('code'));
                $data['itemData'] = $currentNews;
                $viewName = $this->geAddFormByType($currentNews['type']);
                return view($viewName, $data);
                break;
        }
    }

    /**
     * 显示数据导入页面
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function importView(Request $request)
    {
        // 获取登录用户
        $loginUser = Auth::user();

        $data['view'] = $request->input('view');
        $data['code'] = $loginUser['code'];

        return view('v1.form.upload_excel', $data);
    }

    /**
     * 更新数据信息(单元格)
     *
     * @param NoticeRequest $request
     * @return array
     */
    public function updateCellData(NoticeRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新闻代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateNotice($request);

            $bUpdateFlag = $this->checkUpdateAction($request->input('code'));

            if ($bUpdateFlag) {
                // 更新信息
                $successFlag = $this->handleUpdate($request, true);

                if ($successFlag) {
                    $response['rspStatus'] = true;
                    $response['rspMsg'] = '新闻代码[' . $request->input('code') . '],更新成功！';
                }
            } else {
                $response['rspMsg'] = '新闻代码[' . $request->input('code') . '],更新失败，原因：已发布或已审核通过不允许更新！';
            }
        }

        return $response;
    }

    /**
     * 更新数据信息
     *
     * @param NoticeRequest $request
     * @return array
     */
    public function updateData(NoticeRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新闻代码[' . $request->input('code') . '],更新失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateNotice($request);

            $bUpdateFlag = $this->checkUpdateAction($request->input('code'));

            if ($bUpdateFlag) {
                
                //检测是否包含更改是否在手机端显示
                if((isset($request['isShow']))&&($request['isShow'] == 1)){
                    InfoNotice::where('program_code', $request['program_code'])
                        ->where('isShow', 1)
                        ->update([
                            'isShow' => 0,
                        ]);
                }
                
                // 更新信息
                $successFlag = $this->handleUpdate($request, false);

                if ($successFlag) {
                    $response['rspStatus'] = true;
                    $response['rspMsg'] = '新闻代码[' . $request->input('code') . '],更新成功！';
                }
            } else {
                $response['rspMsg'] = '新闻代码[' . $request->input('code') . '],更新失败，原因：已发布或已审核通过不允许更新！';
            }
        }

        return $response;
    }

    /**
     * 新增基本信息
     *bail关键字表示只要第一个验证失败后面就不验了，提高效率
     * @param Request $request
     * @return array
     */
    public function addData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '公告[' . $request->input('code') . '],新增失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $rules['code'] = 'bail|required';
            $rules['title'] = 'bail|required';
            $rules['content'] = 'bail|required';
            $rules['captcha'] = 'bail|required|captcha';
            $messages['code.required'] = '公告代码不能为空';
            $messages['title.required'] = '公告标题不能为空';
            $messages['content.required'] = '公告内容不能为空';
            $messages['captcha.required'] = '验证码不能为空';
            $messages['captcha.captcha'] = '验证码错误';
            $this->validate($request, $rules, $messages);

            if($request['isShow'] == 1){
                InfoNotice::where('program_code', $request['program_code'])
                        ->where('isShow', 1)
                        ->update([
                            'isShow' => 0,
                        ]);
            }
            // 新增信息
            $successFlag = $this->handleAdd($request);
            
            if ($successFlag) {
                
                $response['rspStatus'] = true;
                $response['rspMsg'] = '公告[' . $request->input('code') . '],新增成功！';
            }
        }

        return $response;
    }

    /**
     * 删除基本信息
     *
     * @param NoticeRequest $request
     * @return array
     */
    public function deleteData(NoticeRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新闻代码[' . $request->input('code') . '],删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateNotice($request);

            // 删除信息
            $successFlag = $this->handleDelete($request, false);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '新闻代码[' . $request->input('code') . '],删除成功！';
            }
        }

        return $response;
    }

    /**
     * 批量删除基本信息
     *
     * @param Request $request
     * @return array
     */
    public function deleteBatchData(Request $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '新闻批量删除失败！',
        ];

        if ($request->method() === 'POST') {
            // 删除信息
            $successFlag = $this->handleDelete($request, true);

            if ($successFlag) {
                $response['rspStatus'] = true;
                $response['rspMsg'] = '新闻批量删除成功！';
            }
        }

        return $response;
    }



    ///////////////////////////////////////////////////////////////////
    /// 获取数据功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 分页查询符合条件的列表数据
     *
     * @param int $page 当前页数
     * @param $rows 每页显示条数
     * @param $keywords 搜索关键词
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator 分页对象
     */
    private function getDataList($page = 1, $rows, $keywords)
    {
        if (!isset($keywords) || empty($keywords)) {
            $data = InfoNotice::orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        } else {
            $data = InfoNotice::where('title', 'like', '%' . $keywords . '%')
                ->orderBy('created_at', 'desc')
                ->paginate($rows, ['*'], 'page', $page);
        }
        return $data;
    }

    /**
     * 获取所有新闻栏目列表数据
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    private function getNoticeProgramList()
    {
        $data = InfoNoticeProgram::get(['code', 'name']);
        return $data;
    }


    /**
     * 根据新闻代码获取对应新闻信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getNoticeByCode($code)
    {
        $data = InfoNotice::where('code', $code)->first();
        return $data;
    }

    /**
     * 根据栏目代码获取对应栏目信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getNoticeProgramByCode($code)
    {
        $data = InfoNoticeProgram::where('code', $code)->first();
        return $data;
    }

    /**
     * 根据教职工代码获取对应教职工信息
     *
     * @param $code
     * @return \Illuminate\Database\Eloquent\Model|null|static
     */
    private function getFacultyByCode($code)
    {
        $term = Faculty::where('code', $code)->first();
        return $term;
    }

    /**
     * 格式化显示内容类型
     *
     * @param $val
     * @return string
     */
    private function formateTypeData($val)
    {
        $strFormat = '<span class="layui-bg-cyan">未知</span>';
        switch ($val) {
            case 0:
                $strFormat = '<span class="layui-bg-blue">图文</span>';
                break;
            case 1:
                $strFormat = '<span class="layui-bg-orange">图集</span>';
                break;
            case 2:
                $strFormat = '<span class="layui-bg-red">视频</span>';
                break;
        }
        return $strFormat;
    }

    /**
     * 格式化显示发布信息
     *
     * @param $val
     * @return string
     */
    private function formateMobileShowData($val)
    {
        $strFormat = '<span class="layui-bg-gray">否</span>';
        if ($val) {
            $strFormat = '<span class="layui-bg-green">是</span>';
        }
        return $strFormat;
    }


    /**
     * 检查数据是否允许执行更新操作
     *
     * @param $code
     * @return bool
     */
    private function checkUpdateAction($code)
    {
        $bOK = false;
        $objNews = $this->getNoticeByCode($code);
        if ($objNews['auditStatus'] < 200 || !$objNews['isPublish']) {
            $bOK = true;
        }
        return $bOK;
    }

    /**
     * 根据内容类型获取单条新增数据表单
     *
     * @param $type 0：图文；1：图集；2：视频；
     */
    private function geAddFormByType($type)
    {
        switch ($type) {
            case '0':
                $viewName = 'v1.form.notice_item_text';
                break;
            case '2':
                $viewName = 'v1.form.notice_item_video';
                break;
            default:
                $viewName = 'v1.form.notice_item_text';
                break;
        }
        return $viewName;
    }

    /**
     * 处理数据库返回的content字段json数据
     *
     * @param $json
     * @return string
     */
    private function contentJson2Str($json)
    {
        $data = json_decode($json);
//        $str = $data->content;
        return $data;
    }

    ///////////////////////////////////////////////////////////////////
    /// 验证表单功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理新增、更新信息验证请求
     *
     * @param NoticeRequest $request
     */
    private function validateNotice(NoticeRequest $request)
    {
        $rules = $request->rules();
        if ($request->input("title") !== null) {
            $rules['title'] = 'bail|required';
        }
        if ($request->input("captcha") !== null) {
            $rules['captcha'] = 'bail|required|captcha';
        }
        $messages = $request->messages();
        // 执行表单数据验证
        $this->validate($request, $rules, $messages);
    }

    ///////////////////////////////////////////////////////////////////
    /// 业务逻辑处理功能函数
    ///////////////////////////////////////////////////////////////////
    /**
     * 处理更新信息
     *
     * @param Request $request
     * @param bool $bCell 是否为单元格修改数据
     * @return bool
     */
    private function handleUpdate(Request $request, $bCell)
    {
        $where = $request->input('code');

        if ($bCell) { // 单元格修改
            $attrs = $request->input('attrs');
            $values = $request->input('values');
            // 拼装更新数据数组
            $updateData = array();
            $counter = 0;
            foreach ($attrs as $attr) {
                $updateData[$attr] = $values[$counter];
                $counter++;
            }
        } else { // 表单修改
            // 拼装更新数据数组
            $updateData = [
                'code' => $request->input('code'),
                'title' => $request->input('title'),
                'program_code' => $request->input('program_code'),
                'publisher_code' => $request->input('publisher_code'),
                'type' => $request->input('contentType'),
                'content'=>json_encode($request->input('content')),
                'isShow' => isset($request['isShow']) ? $request->input('isShow') : 0,
                'videoCoverPic' => isset($request['videoCoverPic']) ? $request->input('videoCoverPic') : null,
            ];
        }
        $rspObj = InfoNotice::where('code', $where)->update($updateData);

        return $rspObj;
    }

    /**
     * 处理删除信息
     *
     * @param Request $request
     * @param bool $bBatch 是否为批量数据
     * @return bool
     */
    private function handleDelete(Request $request, $bBatch)
    {
        $where = $request->input('code');

        if ($bBatch) { // 批量删除
            foreach ($where as $code) {
                $rspObj = InfoNotice::where('code', $code)->delete();
            }
        } else { // 单条删除
            $rspObj = InfoNotice::where('code', $where)->delete();
        }

        return $rspObj;
    }

    /**
     * 处理新增信息
     *
     * @param Request $request
     * @return bool
     */
    private function handleAdd(Request $request)
    {
        $contentJson['content'] = $request->input('content');
        // 拼装新增数据数组
        $insertData = [
            'code' => $request->input('code'),
            'title' => $request->input('title'),
            'program_code' => $request->input('program_code'),
            'publisher_code' => $request->input('publisher_code'),
            'type' => $request->input('contentType'),
            'content'=>json_encode($request->input('content')),
            'isShow' => isset($request['isShow']) ? $request->input('isShow') : 0,
            'videoCoverPic' => isset($request['videoCoverPic']) ? $request->input('videoCoverPic') : null,
        ];
        $rspObj = InfoNotice::create($insertData);
        return $rspObj;
    }

    /**
     *处理json转为html
     * @param $content
     */
    private function getContentToHtml($content) {
        $result='';
        foreach ($content as $item){
            $type = $item['type'];
            $value = $item['content'];
            switch ($item['type']) {
                case 'text':
                    $childHtml = "<p>".$value."</p>";
                    $result .=$childHtml;
                    break;
                case 'image':
                    $childHtml ="<p>"."<img src=".$value.">"."</p>";
                    $result .=$childHtml;
                    break;
                default:
            }
        }
        return $result;
    }
}
